<template>
  <div class="app-container">
    <div id="mapContent" v-loading="loading" style="z-index: 1;"></div>
    <div class="button_position">
      <el-button v-if="buttonshow == 'expend'" icon="el-icon-caret-top" @click="onExpend" size="mini"></el-button>
      <el-button v-if="buttonshow == 'putaway'" icon="el-icon-caret-bottom" @click="onPutaway" size="mini"></el-button>
      <div style="margin-top: 3px; border: 1px solid #DCDFE6;">
        <el-collapse-transition>
          <div v-show="buttonshow == 'expend'" style="height: auto; background: white;">
            <el-tooltip class="item" effect="light" content="默认中心点" placement="left">
              <el-row style="border-bottom: 1px solid #DCDFE6; text-align:center;margin:0px 5px;">
                <el-button @click="skipPosition" type="text" style="padding: 8px 5px;"><i class="el-icon-s-promotion"></i></el-button>
              </el-row>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="设置中心点" placement="left">
              <el-row style="text-align:center; margin:0px 5px;">
                <el-button @click="diyPosition" type="text" style="padding: 8px 5px;"><i class="el-icon-s-flag"></i></el-button>
              </el-row>
            </el-tooltip>
          </div>
        </el-collapse-transition>
      </div>
      <!-- <el-button type="primary" @click="setDefaultPosition" >设置中心点</el-button>
      <el-button type="primary" @click="onDefaultPosition">跳转中心点</el-button>
      <el-button type="primary" @click="cancelDefaultPosition">取消中心点</el-button>
      <el-button type="primary" @click="setDefaultPosition" >保存</el-button> -->
    </div>
  </div>
</template>
<script>
import { listTerminalsdb} from "@/api/record/terminalsdb";
import { updateData, listData } from "@/api/basedata/dictdata";
import { gcj2bdString } from "@/utils/coordinate";
import Cookies from "js-cookie";
export default {
  name: 'TerminalMap',
  dicts: ['default_position'],
  data(){
    return {
      dataList: [],
      map: {},
      loading: false,
      // 按钮展示
      buttonshow: 'expend',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        AreaCode: null,
        TerminalID: null,
        TerminalName: null,
        communicateAddress: null,
        TerminalMark: 1,
      },
      position:{
        diylng: '',
        diylat: '',
      },
      promission: false,
      dictLng: {},
      dictLat:{},
    }
  },
  mounted(){
    this.getList()
    this.getDictData()
    setTimeout(() => {
      this.initMap()
    },1000)
  },
  methods: {
    // 跳转中心点
    skipPosition() {
      let point = new T.LngLat(this.dictLng.dictValue, this.dictLat.dictValue)
      this.map.centerAndZoom(point);
    },
    // 自定义中心点  在定义之前中心点还是原来的
    diyPosition() {
      let _this = this
      _this.$confirm('请在地图上选择任意一点作为中心点！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        _this.getLngLat()
      }).catch(() => {
        _this.map.addEventListener("click",function(e){
          _this.map.closeInfoWindow()
        })
      });
    },
    // 获取位置信息添加定位点
    getLngLat(lnglat){
      let _this = this
      _this.map.addEventListener("click",function(e){
        let icon = new T.Icon({
          iconUrl: "http://api.tianditu.gov.cn/img/map/markerA.png",
          iconSize: new T.Point(19, 27),
          iconAnchor: new T.Point(10, 25)
        });
        _this.clearIcon('default')
        const x = e.lnglat.lng;
        const y = e.lnglat.lat; //纵坐标纬度
        let currentpoint = new T.LngLat(x, y); //获取本次标记点位置
        let currentmarker = new T.Marker(currentpoint, {icon: icon});
        currentmarker.id = "default"
        _this.map.addOverLay(currentmarker); // 添加标注点
        _this.$confirm('确认将该点保存为中心点吗？', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
        }).then(() => {
          _this.clearIcon('default')
          _this.map.centerAndZoom(currentpoint)
          let mapType = 'BAIDU'
          let positionArr = gcj2bdString(x, y, mapType)
          _this.dictLng.dictValue= positionArr[0]
          _this.dictLat.dictValue = positionArr[1]
          _this.updateDictData(_this.dictLng)
          _this.updateDictData(_this.dictLat)
          _this.$modal.msgSuccess("默认中心点设置成功");
          _this.map.removeEventListener("click")
          _this.map.addEventListener("click",function(e){
            _this.map.closeInfoWindow()
          })
        }).catch(() => {
          // 删除本地次标记点，切换成上个标记点
          _this.clearIcon('default')
          let lastpoint = new T.LngLat(_this.dictLng.dictValue, _this.dictLat.dictValue);
          let lastmarker = new T.Marker(lastpoint);
          lastmarker.id= "default"
          _this.map.centerAndZoom(lastpoint);
          _this.map.removeEventListener("click")
          _this.map.addEventListener("click",function(e){
            _this.map.closeInfoWindow()
          })
        });
        //
      })
    },
    // 字典数据修改
    updateDictData(form){
      updateData(form).then(() => {})
    },
    // 根据字典主键获取字典数据
    getDictData(){
      let params = {
        dictType: 'default_position'
      }
      listData(params).then(response => {
        let mapType = 'GAODE'
        let positionArr = gcj2bdString(response.rows[1].dictValue, response.rows[0].dictValue, mapType)
        this.dictLng = response.rows[1]
        this.dictLat = response.rows[0]
        this.dictLng.dictValue = positionArr[0]
        this.dictLat.dictValue = positionArr[1]
      });
    },
    // 删除指定标注
    clearIcon(e) {
      let that = this;
      let newMarker = that.map.getOverlays(); // 获取到了地图上的所有点
      for (let n = 0; n < newMarker.length; n++) {// 遍历地图上点
        if (e == newMarker[n].id) {// 判断
          that.map.removeOverLay(newMarker[n]);// 执行删除方法
        }
      }
    },
     // 展开
     onExpend(){
      this.buttonshow = 'putaway'
    },
    // 收起
    onPutaway(){
      this.buttonshow = 'expend'
    },
    /** 查询大档案列表 */
    getList() {
      this.loading = true
      listTerminalsdb(this.queryParams).then(response => {
        let pageData = response.rows
        pageData.forEach((item) => {
          if(item.lng != null && item.lng != '' && item.lat != null && item.lat != ''){
            let mapType = 'GAODE'
            let positionArr = gcj2bdString(item.lng, item.lat, mapType)
            let newlng = positionArr[0]
            let newlat = positionArr[1]
            let keys = Object.keys(item)
            for(let i = 0; i < keys.length; i++){
              if(item[keys[i]] == null){
                item[keys[i]] = ''
              }
            }
            let dataItemList = [newlng, newlat,`${item.TerminalName}`,`${item.TerminalID}`, `${item.SupplierID}`, `${item.UserID}`,`${item.IMEI}`,`${item.communicateAddress}`,`${item.InstallAddress}`,`${item.TypeID}`,`${item.Caliber}`]
            this.dataList.push(dataItemList)
          }
        })
        if(response.rows.length == this.queryParams.pageSize){
          this.queryParams.pageNum += 1
          this.getList()
        }
        this.loading = false
      })
    },
    initMap(){
      // let icon = new T.Icon({
      //   iconUrl: "http://api.tianditu.gov.cn/img/map/markerA.png",
      //   iconSize: new T.Point(19, 27),
      //   iconAnchor: new T.Point(10, 25)
      // });
      let _this = this
      _this.map = new T.Map("mapContent");
      _this.map.disableDoubleClickZoom()
      _this.map.enableDrag();
      let point = new T.LngLat( this.dictLng.dictValue, this.dictLat.dictValue)
      let defaultmarker = new T.Marker(point);
      // let defaultmarker = new T.Marker(point, {icon: icon});
      defaultmarker.id = 'default'
      // _this.map.addOverLay(defaultmarker);
      _this.map.centerAndZoom(point, 10);
      for(let i=0;i<this.dataList.length;i++){
        let marker = new T.Marker(new T.LngLat(this.dataList[i][0],this.dataList[i][1]));  // 创建标注
        let content = 
        "<div style='margin:0px;'>" +
          "<div style='margin:10px 10px; '>" +
          `<div>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">设备名称: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][2]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">设备编号: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][3]}</span><br> 
            <span style="font-weight:bold; font-size:14px; color: #1890ff">厂家编号: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][4]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">用户编号: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][5]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IMEI: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][6]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">通讯地址: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][7]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">安装地址: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][8]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">表&nbsp;&nbsp;型&nbsp;&nbsp;号: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][9]}</span><br>
            <span style="font-weight:bold; font-size:14px; color: #1890ff">口&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;径: </span><span style="color: #323232; font-size: 14px;">&nbsp;&nbsp;${this.dataList[i][10]}</span>` +
          "</div>" +
          "</div>";
        _this.map.addOverLay(marker)               // 将标注添加到地图中
        _this.addClickHandler(content,marker);
        _this.map.addEventListener("click",function(e){
          _this.map.closeInfoWindow()
        })
      }
    },
    addClickHandler(content,marker){
      let _this = this
      marker.addEventListener("click",function(e){
        _this.openInfo(content,e)
      });
    },
    openInfo(content,e){
      let point = e.lnglat;
      // let marker = new T.Marker(point);// 创建标注
      let markerInfoWin = new T.InfoWindow(content,{offset:new T.Point(0,-30)}); // 创建信息窗口对象
      this.map.openInfoWindow(markerInfoWin,point); //开启信息窗口
    }
  },
}
</script>
<style lang="scss" scoped>
.app-container{
  margin: 0 auto;
}
#mapContent{
  height: calc(100vh - 86px);
  width: 100%;
}
::v-deep .tdt-infowindow-content-wrapper, .tdt-infowindow-tip {
  background: rgb(255, 255,255);
}
::v-deep .tdt-infowindow-content-wrapper {
  border-top: 3px solid #1890ff;
  padding: 10px;
}
::v-deep .tdt-infowindow-content {
  margin: 5px;
}
::v-deep .tdt-infowindow-tip-container {
    display: none;
}
.button_position{
  position: fixed;
  top: 100px;
  right: 30px;
  z-index: 299;
}
::v-deep .tdt-control > div > img {
  display: none;
}
::v-deep .tdt-container .tdt-control-copyright, .tdt-container .tdt-control-scale {
  display: none;
}

</style>
<style>
.el-tooltip__popper.is-light {
    background: #FFFFFF;
    border: none !important;
    margin-right: 10px !important;
}
</style>